package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.SaveTimeLine;
import com.tanhua.mondb.Movement;
import com.tanhua.mondb.MovementTimeLine;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements  MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SaveTimeLine saveTimeLine;
    /*
    * 发布动态
    * */
    @Override
    public void publish(Movement movement) {
        try {
            //将动态对象保存早动态表中
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //使用异步查询全部的好友，并写入时间线表，提高效率
            saveTimeLine.save(movement.getUserId(),movement.getId());
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    /*
    * 查询个人动态
    * */
    @Override
    public PageResult movementsByUserId(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize)
                           .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pageResult = new PageResult(page, pageSize, 0L, movements);
        return pageResult;
    }
    /*
    * friendId是传递过来的userId,通过friendId来查看好友发布的动态id，在通过动态id查询动态
    * */
    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pageSize, Long friendId) {
        //构建friensId查询时间线表，得到时间线表中好友的发布动态的id
        Criteria criteria = Criteria.where("friendId").is(friendId);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //通过好友动态id在去动态表中查询动态
        Query criteriaQuery = Query.query(Criteria.where("id").in(movementId));
        List<Movement> movements = mongoTemplate.find(criteriaQuery, Movement.class);
        return movements;
    }
    /*
    * 推荐动态没有数据的情况下
    * */
    @Override
    public List<Movement> randomMovements(Integer pageSize) {
        //使用mongoDB中的内置的随机数据类
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(pageSize));

        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);

        return movements.getMappedResults();
    }
    /*
    * 推荐动态中有数据的情况下
    * */
    @Override
    public List<Movement> findMovementByIds(List<Long> pids) {
        Query query = Query.query(Criteria.where("pId").in(pids));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }
    /*
    * 查看单个动态
    * */
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }
}
